<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2017/6/9
 * Time: 17:34
 */

namespace frontend\controllers;

use common\models\Company;
use common\models\CompanyInfo;
use common\models\Goods;
use common\models\GoodsAttributeValues;
use common\models\News;
use common\models\ShopOrder;
use common\models\OrderComment;
use common\models\OrderGoodsRelation;
use common\models\User;
use common\models\User1;
use common\models\UserAddress;
use common\models\VirtualOrderShip;
use yii;
class UserShopController extends BaseApiController
{

    protected  $not_del_code;           //评价未删除值
    protected  $not_audited_code;       //评价未审核值
    protected  $order_shiped_code;
    protected  $order_complete_code;
    protected  $virtual_order_code;
    protected $spent_huiwenbi_code;
    protected $received_huiwenbi_code;

    public function init()
    {
        parent::init(); // TODO: Change the autogenerated stub

        $this->not_del_code = 0;
        $this->not_audited_code = 0;
        $this->order_shiped_code = 3;
        $this->order_complete_code = 4;
        $this->virtual_order_code = 2;
        $this->spent_huiwenbi_code = 2;
        $this->received_huiwenbi_code = 1;
    }

    /**
     * 公司信息
     */
    public function actionCompanyInfo(){
        $company_id = yii::$app->request->post('company_id', 0);
        if(!$company_id) $this->_errorData('30000', '参数错误');

        $company_info_model = new CompanyInfo();
        $ret = $company_info_model::find()->where(['company_id'=>$company_id])->asArray()->one();
        $ret || $ret = [];

        $this->_successData($ret);
    }

    /**
     * 添加/编辑 收货地址
     */
    public function actionAddAddress(){
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;

        if(!$company_id) $this->_errorData('3000', '参数错误');

        $address_id = isset($this->params['address_id']) ? $this->params['address_id'] : 0;
        $consignee = isset($this->params['consignee']) ? $this->params['consignee'] : 0;
        $prov    = isset($this->params['prov']) ? $this->params['prov'] : 0;
        $city    = isset($this->params['city']) ? $this->params['city'] : 0;
        $county  = isset($this->params['county']) ? $this->params['county'] : 0;
        $address = isset($this->params['address']) ? $this->params['address'] : 0;
        $zipcode = isset($this->params['zipcode']) ? $this->params['zipcode'] : 0;
        $mobile  = isset($this->params['mobile']) ? $this->params['mobile'] : 0;
        $id_number = isset($this->params['id_number']) ? $this->params['id_number'] : '';
        $is_default = isset($this->params['is_default']) ? $this->params['is_default'] : 0;

        if(!$consignee || !$prov || !$city || !$county || !$address || !$zipcode || !$mobile) $this->_errorData('3002', '参数错误');

//        $user_info = $this->getUserInfoByToken($user_token);
        $user_info = $this->_getUserData();

        if(!$user_info || !$user_info['userId']) $this->_errorData('3001', 'ERROR');

        //如果勾选设为默认，则把已有的全部设置为 0
        if($is_default == 1){
            UserAddress::updateAll(['is_default'=>0], ['user_id'=>$user_info['userId'], 'company_id'=>$company_id]);
        }

        if($address_id){
            $user_addr_model = UserAddress::findOne($address_id);
        }else{
            $user_addr_model = new UserAddress();
        }

        $user_addr_model->company_id = $company_id;
        $user_addr_model->user_id    = $user_info['userId'];
        $user_addr_model->consignee  = $consignee;
        $user_addr_model->prov   = $prov;
        $user_addr_model->city   = $city;
        $user_addr_model->county = $county;
        $user_addr_model->address = $address;
        $user_addr_model->phone   = $mobile;
        $user_addr_model->zipcode  = $zipcode;
        $user_addr_model->id_number = $id_number;
        $user_addr_model->is_default = $is_default;
        $user_addr_model->create_time = time();
        $ret = $user_addr_model->save();

        if($ret !== false) $this->_successData('添加成功');

        $this->_errorData('3004', '添加失败');
    }

    /**
     * 获取用户收货地址
     */
    public function actionGetUserAddress(){
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;
        $address_id = isset($this->params['address_id']) ? $this->params['address_id'] : 0;

        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $size = isset($this->params['size']) ? $this->params['size'] : 10;

        if(!$company_id) $this->_errorData('4000', '参数错误');

        $user_info = $this->_getUserData();
        if(!$user_info || !$user_info['userId']) $this->_errorData('4001', '参数错误');

        $and_where = '1 = 1';
        if($address_id) $and_where .= " AND address_id = {$address_id}";

        $total = false;$list = false;

        $offset = ($page - 1) * $size;
        $list = UserAddress::find()
            ->select(['address_id', 'consignee', 'prov', 'city', 'county', 'address', 'phone', 'id_number', 'zipcode', 'is_default'])
            ->where(['user_id'=>$user_info['userId'], 'is_del'=>0])
            ->andWhere($and_where)
            ->orderBy('is_default DESC')
            ->offset($offset)
            ->limit($size)
            ->asArray()
            ->all();

        $total = UserAddress::find()
            ->where(['user_id'=>$user_info['userId'], 'is_del'=>0])
            ->andWhere($and_where)
            ->count();

        $total || $total = 0;

        $return_data['total'] = $total;
        $return_data['list'] = $list;

        $this->_successData($return_data);
    }

    /**
     * 删除用户收货地址
     */
    public function actionDelUserAddress(){
        $company_id = yii::$app->request->post('company_id');
        $address_id = yii::$app->request->post('address_id');
        if(!$address_id) $this->_errorData('9000', '参数错误');

        $user_info = $this->_getUserModel();
        if(!$user_info) $this->_errorData('9002', '请先登录');

        $del_address_ret = UserAddress::updateAll(['is_del'=>1], ['address_id'=>$address_id]);
        if($del_address_ret) $this->_successData('删除成功');

        $this->_errorData('9001', '删除失败');
    }

    /**
     * 提交订单
     */
    public function actionConfirmOrder()
    {
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;
        $goods_id   = isset($this->params['goods_id']) ? $this->params['goods_id'] : 0;
        $goods_num  = isset($this->params['goods_num']) ? $this->params['goods_num'] : 0;
        $address_id = isset($this->params['address_id']) ? $this->params['address_id'] : 0;
        $goods_attr_id = isset($this->params['goods_attr_id']) ? $this->params['goods_attr_id'] : 0;
        //$virtual_goods_id = isset($this->params['virtual_goods_id']) ? $this->params['virtual_goods_id'] : 0;
        $freight = isset($this->params['goods_attr_id']) ? round($this->params['freight'], 2) : 0;
        $order_remarks = isset($this->params['remarks']) ? $this->params['remarks'] : '';
        $total_price   = isset($this->params['total_price']) ? $this->params['total_price'] : 0;     //前端计算的价格

        if(!$company_id || !$goods_id || !$goods_num || !$total_price || !$address_id) $this->_errorData('5006', '参数错误');

        /* 校验用户信息 */
        $user_info = $this->_getUserData();
        $all_user_info = User1::findOne($user_info['userId'])->toArray();
        $user_info['amount'] = $all_user_info['amount'];

        if(!$user_info) $this->_errorData('5000', '用户信息错误，请重新登陆');

        /* 商品信息 */
        $goods_info = Goods::find()
            ->alias('g')
            ->select('g.*, gav.*')
            ->leftJoin('vrshop.goods_attribute_values gav', 'g.goods_id = gav.goods_id AND gav.values_id ='.$goods_attr_id)
            ->where(['g.goods_id'=>$goods_id])
            ->asArray()
            ->one();
        if(!$goods_info) $this->_errorData('5001', '商品信息错误，请重新提交订单');
        if($goods_info['is_recovery'] == 1) $this->_errorData('50011', '商品已被回收');

        $admin_goods_price = $goods_info['price'] ? $goods_info['price'] : $goods_info['huiwenbi'];
        $admin_goods_stock = $goods_info['stock'] ? $goods_info['stock'] : $goods_info['goods_stock'];

        //订单类型
        $order_type = $goods_info['goods_type'] ? $goods_info['goods_type'] : 1;

        //下架了
        if($goods_info['is_shelves'] == 0) $this->_errorData('5002', '此商品已经下架');

        //库存
        if($admin_goods_stock <= 0 || $goods_num > $admin_goods_stock) $this->_errorData('5003', '库存不足');

        //校验订单总额
        if($goods_info['freight_type'] == 0){
            //全国价格
            $admin_total_price =  round($admin_goods_price * $goods_num + $goods_info['freight'], 2);
            $freight = $goods_info['freight'];
        }elseif($goods_info['freight_type'] == 1){
            /* 省外价格  判断是不是省外发货  收货地址是外省的时候收费 */
            $user_addr_info = UserAddress::findOne($address_id)->toArray();
            $company_in_city = Company::findOne($company_id)->toArray();

            if($user_addr_info['prov'] == $company_in_city['prov']){
                $freight = 0;
            }else{
                $freight = $goods_info['freight'];
            }
            $admin_total_price = round($admin_goods_price * $goods_num + $freight, 2);
        }
        if($total_price != $admin_total_price) $this->_errorData('5004', '订单信息有误');

        //校验用户汇闻币数量
        if($user_info['amount'] < $admin_total_price) $this->_errorData('5558', '汇闻币不足');

        $transaction = yii::$app->db->beginTransaction();
        try{
            //订单入库
            $insert_order_ret = yii::$app->db->createCommand()->insert('vrshop.shop_order', [
                'company_id' => $company_id,
                'user_id' => $user_info['userId'],
                'order_number' => ShopOrder::_createOsn($user_info['userId'], 0, 0),
                'huiwenbi' => $admin_total_price,
                'reciver_id' => $address_id,
                'freight' => $freight,
                'order_remarks' => $order_remarks,
                'status' => '1',
                'is_del' => '0',
                'create_time' => time(),
            ])->execute();
            if(!$insert_order_ret) throw new \Exception('增加订单失败');

            $order_id = yii::$app->db->getLastInsertID();

            //订单 商品表
            $insert_order_goods_ret = yii::$app->db->createCommand()->insert('vrshop.order_goods_relation',[
                'order_id' => $order_id,
                'goods_id' => $goods_id,
                'goods_num' => $goods_num,
                //'virtual_goods_id' => $virtual_goods_id,
                'attribute_value_id' => $goods_attr_id,
            ])->execute();
            if(!$insert_order_goods_ret) throw new \Exception('增加订单失败');

            //为用户减汇闻币
            $update_user_ret = yii::$app->db->createCommand()
                ->update(
                    'vruser1.user',
                    ['amount' => new yii\db\Expression("amount - {$admin_total_price}")],
                    "user_id = {$user_info['userId']} AND amount > 0"
                )
                ->execute();
            if(!$update_user_ret) throw new \Exception('扣除汇闻币失败');

            //为商品减库存
            $goods_updata_ret = yii::$app->db->createCommand()->update('vrshop.goods',[
                'goods_stock' => new yii\db\Expression("goods_stock - {$goods_num}")
            ], "goods_id = {$goods_id} AND goods_stock > 0")->execute();
            if(!$goods_updata_ret) throw new \Exception('减库存失败');

            //减属性库存
            if($goods_attr_id){
                $up_goods_attr_stock_ret = yii::$app->db->createCommand()->update('vrshop.goods_attribute_values', [
                    'stock' => new yii\db\Expression("stock - $goods_num"),
                ], "values_id = {$goods_attr_id}")->execute();
                if(!$up_goods_attr_stock_ret) throw new \Exception('减属性库存失败');
            }

            //更新用户汇闻币明细  user_amount
            $surplus = (int)($user_info['amount'] - $admin_total_price);
            $insert_user_amount_ret = yii::$app->db->createCommand()->insert('vruser1.user_amount', [
                'user_id' => $user_info['userId'],
                'operate_cnt' => $admin_total_price,
                'surplus' => $surplus,
                'operate' => $this->spent_huiwenbi_code,
                'operate_name' => '兑换商品:'.$goods_info['goods_id'],
                'created_at' => date('Y-m-d H:i:s', time()),
            ])->execute();
            if(!$insert_user_amount_ret) throw new \Exception('更新用户汇闻币明细错误');

         $transaction->commit();
            $this->_successData('提交订单成功');
        }catch(\Exception $e){
            $this->_errorData('5005', '订单提交失败，'.$e->getMessage());
        }
        $this->_errorData('5006', '订单提交失败，请重试');
    }

    /**
     * 用户 订单列表
     */
    public function actionGetOrderList(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $size = isset($this->params['size']) ? $this->params['size'] : 10;
        $goods_name = isset($this->params['goods_name']) ? $this->params['goods_name'] : '';
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;
        $company_name = isset($this->params['company_name']) ? $this->params['company_name'] : '';
        $order_status = isset($this->params['order_status']) ? $this->params['order_status'] : 0;           // 0：全部  1：代发货  2：已发货 3已收获  4 待评价  5 已评价


//        $user_info = $this->getUserInfoByToken($user_token);
        $user_info = $this->_getUserData();
        if(!$user_info) $this->_errorData('6001', '用户信息错误');

        $order_list = ShopOrder::GetOrder('', $goods_name, $company_name, $user_info['userId'], $order_status, $page, $size);

        $this->_successData($order_list);
    }

    /**
     * 订单详情
     */
    public function actionGetOrderInfo(){
        $order_id   = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        if(!$order_id) $this->_errorData('6020', '参数错误');

        $user_info = $this->_getUserData();
        if(!$user_info) $this->_errorData('6021', '用户信息错误');

        $order_info = ShopOrder::GetOrder($order_id, '', '', $user_info['userId']);
        foreach ($order_info as &$order){
            if($order['goods_type'] == $this->virtual_order_code){
                $order['virtual_ship_info'] = VirtualOrderShip::find()
                     ->alias('vos')
                    ->select(['vos.ship_id', 'vgi.serial_number', 'vgi.password', 'vgi.deadline'])
                     ->leftJoin('vrshop.virtual_goods_info vgi', 'vos.details_id = vgi.details_id')
                     ->where(['vos.order_id'=>$order['order_id']])
                     ->asArray()
                     ->all();
            }else{
                $order['virtual_ship_info'] = '';
            }
        }
        unset($order);

        $this->_successData($order_info);
    }

    /**
     * 推荐商品
     */
    public function actionRecommendGoods(){
        $company_id = isset($this->params['company_id']) ? $this->params['company_id'] : 0;
        $order_id   = isset($this->params['order_id']) ? $this->params['order_id'] : 0;
        if(!$company_id || !$order_id) $this->_errorData('6030', '参数错误');

        $recommend_list = Goods::find()
            ->select(['goods_id', 'goods_name', 'banner_image', 'tags', 'huiwenbi', 'market_price', 'goods_introduce'])
            ->where(['company_id'=>$company_id, 'recommend_status'=>2])
            ->limit(4)
            ->asArray()
            ->all();

        if(empty($recommend_list)){
            //查找销量最多的
            $sql = 'SELECT goods_id,COUNT(id) as total FROM vrshop.order_goods_relation GROUP BY goods_id ORDER BY total DESC LIMIT 4';
            $connection  = Yii::$app->db;
            $command = $connection->createCommand($sql);
            $result  = $command->queryAll();

            $result || $result = [];
            $recommend_list = [];
            foreach ($result as $item) {
                $recommend_list[] = Goods::find()
                    ->select(['goods_id', 'goods_name', 'banner_image', 'tags', 'huiwenbi', 'market_price', 'goods_introduce'])
                    ->where(['goods_id'=>$item['goods_id']])
                    ->asArray()
                    ->one();
            }
        }

        $this->_successData($recommend_list);
    }

    /**
     * 用户确认收货
     * @param $order_id
     * @return array
     */
    public function actionConfirmReceipt(){
        $company_id = yii::$app->request->post('company_id', 0);
        $order_id   = yii::$app->request->post('order_id', 0);
        if(!$order_id) $this->_errorData('8000', '参数错误');

        $order_info = ShopOrder::findOne($order_id)->toArray();
        if($order_info['status'] != $this->order_shiped_code || !$order_info['ship_time']) $this->_errorData('8001', '订单状态错误');

        //对比下单人
        $user_info = $this->_getUserData();
        if($user_info['userId'] != $order_info['user_id']) $this->_errorData('8002', '订单信息错误');

        $up_order_status_ret = ShopOrder::updateAll(['status'=>$this->order_complete_code, 'complete_time'=>time()], ['order_id'=>$order_id]);
        if($up_order_status_ret) $this->_successData('确认收货成功');
        $this->_errorData('8003', '确认收货失败');
    }


    /**
     * 订单评价
     */
    public function actionOrderComment(){
        $order_id   = yii::$app->request->post('order_id', 0);
        $comment    = yii::$app->request->post('comment', '');
        $goods_score = yii::$app->request->post('goods_score', 0);
        if(!$order_id || !$comment) $this->_errorData('7000', '参数错误');

        $user_info = $this->_getUserData();
        if(!$user_info || !$user_info['userId']) $this->_errorData('7001', '用户信息错误');

        $order_info = ShopOrder::GetOrder($order_id, '', '', $user_info['userId']);
        if($order_info[0]['status'] != $this->order_complete_code) $this->_errorData('7003', '此订单不能评价');

        if($user_info['userId'] != $order_info[0]['user_id']) $this->_errorData('70031', '此订单已经评论或未完成');

        $comment_exist = OrderComment::find()->where(['user_id'=>$user_info['userId'], 'order_id'=>$order_id])->count();
        if($comment_exist) $this->_errorData('70032', '您已评价');

        $ip_addr = yii::$app->request->userIP;
        $ret = OrderComment::AddComment($order_info[0]['company_id'], $order_id, $order_info[0]['goods_id'], $user_info['userId'], $comment, $goods_score, $ip_addr, $this->not_audited_code, $this->not_del_code);
        if($ret){
            $this->_successData('评论成功');
        }
        $this->_errorData('7002', '评论失败');
    }

    public function actionGetFreight(){
        $goods_id   = yii::$app->request->post('goods_id', 0);
        $address_id = yii::$app->request->post('address_id', 0);
        if(!$address_id || !$goods_id) $this->_errorData('8000', '参数错误');

        $goods_info   = Goods::findOne($goods_id)->toArray();
        $address_info = UserAddress::findOne($address_id)->toArray();
        $company_id   = $goods_info['company_id'];
        $freight = ShopOrder::getFreight($company_id, $goods_info, $address_info);
        $this->_successData($freight);
    }


}